/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.fileManage.web;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.api.web.business.fileManage.FileManageApi;
import org.opsli.api.web.business.patrolStation.PatrolStationRestApi;
import org.opsli.api.wrapper.business.fileManage.FileManageModel;
import org.opsli.api.wrapper.business.patrolStation.PatrolStationModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.modulars.business.fileManage.entity.FileManage;
import org.opsli.modulars.business.fileManage.service.IFileManageService;
import org.opsli.modulars.business.patrolStation.entity.PatrolStation;
import org.opsli.modulars.business.patrolStation.service.IPatrolStationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 文件管理 Controller
 *
 * @author zk
 * @date 2021-09-14 15:53:53
 */
@Api(tags = PatrolStationRestApi.TITLE)
@Slf4j
@ApiRestController("/business/file")
public class FileManageRestController extends BaseRestController<FileManage, FileManageModel, IFileManageService>
        implements FileManageApi {


    @Override
    public void download(HttpServletRequest request,HttpServletResponse response) {
        FileManage manage=IService.getFile("7");
        String apkPath = manage.getDocpath()+manage.getFilepath();//apk的path
        //new 一个apk的文件对象
        File file = new File(apkPath);
        try {
            if(file.exists()){
                // 以流的形式下载文件。

                //先以输入流把文件输入到buffer中，再以输出流的形式输出
                InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        }catch(Exception e) {
            System.out.println("下载文件错误"+e.getMessage());
        }
    }

    /**
     * 阀门井app版本更新
     * @param request
     * @param response
     */
    @Override
    public void valveDownload(HttpServletRequest request, HttpServletResponse response) {
        FileManage manage=IService.getFile("221");
        String apkPath = manage.getDocpath()+manage.getFilepath();//apk的path
        //new 一个apk的文件对象
        File file = new File(apkPath);
        try {
            if(file.exists()){
                // 以流的形式下载文件。

                //先以输入流把文件输入到buffer中，再以输出流的形式输出
                InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        }catch(Exception e) {
            System.out.println("下载文件错误"+e.getMessage());
        }
    }

    @Override
    public void gasWorkDownload(HttpServletRequest request, HttpServletResponse response) {
        FileManage manage=IService.getFile("301"); //2.2.22版本
        String apkPath = manage.getDocpath()+manage.getFilepath();//apk的path
        //new 一个apk的文件对象
        File file = new File(apkPath);
        try {
            if(file.exists()){
                // 以流的形式下载文件。

                //先以输入流把文件输入到buffer中，再以输出流的形式输出
                InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        }catch(Exception e) {
            System.out.println("下载文件错误"+e.getMessage());
        }
    }

    @Override
    public void gasSgjlDownload(HttpServletRequest request, HttpServletResponse response) {
        FileManage manage=IService.getFile("401"); //2.2.22版本
        String apkPath = manage.getDocpath()+manage.getFilepath();//apk的path
        //new 一个apk的文件对象
        File file = new File(apkPath);
        try {
            if(file.exists()){
                // 以流的形式下载文件。

                //先以输入流把文件输入到buffer中，再以输出流的形式输出
                InputStream fis = new BufferedInputStream(new FileInputStream(apkPath));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        }catch(Exception e) {
            System.out.println("下载文件错误"+e.getMessage());
        }
    }


    @Override
    public void getImages(HttpServletRequest request,HttpServletResponse response){
        InputStream fis = null;
        OutputStream os = null ;
        URL url = null;
        HttpURLConnection httpUrl = null;
        String id=request.getParameter("id");
        FileManage manage=IService.getFile(id);
        String path="";
        if(manage!=null){
            path = manage.getDocpath()+manage.getFilepath();
            try {
                fis = new FileInputStream(path);
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
//                httpUrl.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }



    @Override
    public void getIVideos(HttpServletRequest request,HttpServletResponse response) {
       /* InputStream fis = null;
        OutputStream os = null;
        URL url = null;
        HttpURLConnection httpUrl = null;
        String id = request.getParameter("id");
        FileManage manage = IService.getFile(id);
        String path = "";
        if (manage != null) {
            try {
                path = manage.getDocpath() + manage.getFilepath();
                fis = new FileInputStream(path);
                response.setContentType("video/mpeg4"); // 设置返回的文件类型
                os = response.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
//                httpUrl.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
       /* try {

            String id=request.getParameter("id");
            FileManage manage=IService.getFile(id);

                        File file = new File(manage.getDocpath() + manage.getFilepath());
                         response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                         response.setHeader("Content-Disposition", "attachment; filename="+file.getName().replace(" ", "_"));
                         InputStream iStream = new FileInputStream(file);
                         IOUtils.copy(iStream, response.getOutputStream());
                        response.flushBuffer();
                     } catch (java.nio.file.NoSuchFileException e) {
                         response.setStatus(HttpStatus.NOT_FOUND.value());
                     } catch (Exception e) {
                         response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                     }
    }*/
        response.reset();
        //获取从那个字节开始读取文件
        String rangeString = request.getHeader("Range");
        String id = request.getParameter("id");
        FileManage manage = IService.getFile(id);
        try {
            //获取响应的输出流
            OutputStream outputStream = response.getOutputStream();
            File file = new File(manage.getDocpath() + manage.getFilepath());
            if (file.exists()) {
                RandomAccessFile targetFile = new RandomAccessFile(file, "r");
                long fileLength = targetFile.length();
                //播放
                if (rangeString != null) {

                    long range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                    //设置内容类型
                    response.setHeader("Content-Type", "video/mp4");
                    //设置此次相应返回的数据长度
                    response.setHeader("Content-Length", String.valueOf(fileLength - range));
                    //设置此次相应返回的数据范围
                    response.setHeader("Content-Range", "bytes " + range + "-" + (fileLength - 1) + "/" + fileLength);
                    //返回码需要为206，而不是200
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                    //设定文件读取开始位置（以字节为单位）
                    targetFile.seek(range);
                } else {//下载

                    //设置响应头，把文件名字设置好
                    response.setHeader("Content-Disposition", "attachment; filename=" + "6000001371140194.mp4");
                    //设置文件长度
                    response.setHeader("Content-Length", String.valueOf(fileLength));
                    //解决编码问题
                    response.setHeader("Content-Type", "application/octet-stream");
                }


                byte[] cache = new byte[1024 * 300];
                int flag;
                while ((flag = targetFile.read(cache)) != -1) {
                    outputStream.write(cache, 0, flag);
                }
            } else {
                String message = "file:" + "6000001371140194.mp4" + " not exists";
                //解决编码问题
                response.setHeader("Content-Type", "application/json");
                outputStream.write(message.getBytes(StandardCharsets.UTF_8));
            }

            outputStream.flush();
            outputStream.close();

        } catch (FileNotFoundException e) {

        } catch (IOException e) {

        }
    }

    }
